package com.kkb.controller.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.kkb.bean.AnthologyTable;
import com.kkb.bean.FileTable;
import com.kkb.bean.TagsTable;
import com.kkb.service.file.AnthologyTableService;
import com.kkb.service.file.AnthologyTagsService;
import com.kkb.service.file.FileAnthologyTableService;
import com.kkb.service.file.TagsTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author 何世鹏
 * @Date 2021/4/14 11:21
 */
@RestController
public class AnthologyTableController {
    @Autowired
    private AnthologyTableService anthologyTableService;

    @Autowired
    private TagsTableService tagsTableService;

    @Autowired
    private AnthologyTagsService anthologyTagsService;

    @Autowired
    private FileAnthologyTableService fileAnthologyTableService;

    /**
     * 查询文集信息列表
     *
     * @param req 请求
     * @param resp 响应
     * @param state 0：审核中  1：已上架  2：未通过
     * @return json格式
     */
    @GetMapping("/get/anthology/list")
    public String getList(HttpServletRequest req, HttpServletResponse resp,Integer state){
        String list = anthologyTableService.getList(req, resp, state);
        return list;
    }

    /**
     * 添加文集
     *
     * @param req 请求
     * @param resp 响应
     * @param file 上传的封面
     * @param anthologyTable 文集信息
     * @return 添加成功/失败
     */
    @PostMapping("/add/anthology")
    public String add(HttpServletRequest req, HttpServletResponse resp, @RequestParam("file") MultipartFile file, AnthologyTable anthologyTable){
        //原始名称-封面
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("文件名称：" + fileName);
        String realPath = req.getServletContext().getRealPath("/upload/img") + "/";
        System.out.println("路径：" + realPath);

        try {
            file.transferTo(new File(realPath + fileName));
            anthologyTable.setAnthologyCoverPath(fileName);
            System.out.println("上传成功:" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("上传失败");
            return "上传失败";
        }
        //添加标签
        List<TagsTable> tags = anthologyTable.getTags();
        if (tags != null) {
            for (TagsTable tag : tags) {
                tagsTableService.addTags(req, resp, tag);
            }
        }
        Boolean aBoolean = anthologyTableService.add(req, resp, anthologyTable);
        return aBoolean?"添加成功":"添加失败";
    }

    /**
     * 逻辑删除文集
     *
     * @param req 请求
     * @param resp 响应
     * @param id 文集ID
     * @return 删除成功
     */
    @DeleteMapping("/del/anthology")
    public String del(HttpServletRequest req, HttpServletResponse resp, Integer id) {
        anthologyTableService.delAnthology(req, resp, id);
        return "删除成功！";
    }

    /**
     * 查询文集信息
     *
     * @param req 请求
     * @param resp 响应
     * @param id 文集ID
     * @return 文集信息
     */
    @GetMapping("/select/anthology")
    public String getById(HttpServletRequest req, HttpServletResponse resp, Integer id){
        AnthologyTable anthologyTable = anthologyTableService.selectById(req, resp, id);
        return JSON.toJSONString(anthologyTable);
    }

    /**
     * 更新文集信息
     *
     * @param req 请求
     * @param resp 响应
     * @param file 文集封面
     * @param anthologyTable 文集信息
     * @return 修改成功/修改失败
     */
    @PutMapping("/update/anthology")
    public String update(HttpServletRequest req,HttpServletResponse resp,@RequestParam("file") MultipartFile file,AnthologyTable anthologyTable) {
        if (file != null) {
            //更新封面
            //原始名称-封面
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println("文件名称：" + fileName);
            String realPath = req.getServletContext().getRealPath("/upload/img") + "/";
            System.out.println("路径：" + realPath);

            try {
                file.transferTo(new File(realPath + fileName));
                anthologyTable.setAnthologyCoverPath(fileName);
                System.out.println("上传成功:" + fileName);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("上传失败");
                return "上传失败";
            }
        }
        List<TagsTable> tags = anthologyTable.getTags();
        if (tags != null) {
            //更新标签
            //1.先去标签关系表把原有关系删除
            anthologyTagsService.del(req,resp,anthologyTable.getAnthologyId());
            //2.重新建立关系
            for (TagsTable tag : tags) {
                tagsTableService.addTags(req, resp, tag);
            }
        }
        List<FileTable> fileTable = anthologyTable.getFileTable();
        if (fileTable != null && fileTable.size() >= 3) {
            //更新关联文档
            //1.删除原有文档关联
            fileAnthologyTableService.del(req,resp,anthologyTable.getAnthologyId());
            //2.重新建立关联
        }else {
            return "修改失败";
        }
        Boolean update = anthologyTableService.update(req, resp, anthologyTable);
        return update?"修改成功":"修改失败";
    }

    /**
     * 下载文集
     *
     * @param req    请求
     * @param resp   响应
     * @param anthologyId 文件id
     * @return 下载文件流
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/download/anthology")
    public ResponseEntity<byte[]> download(HttpServletRequest req, HttpServletResponse resp, Integer anthologyId) throws UnsupportedEncodingException {
        ArrayList<String> filePathArray = anthologyTableService.download(req, resp, anthologyId);
        if (filePathArray != null) {
            String zipName = UUID.randomUUID() + ".zip";
            String realPath = req.getServletContext().getRealPath("/upload/file") + "/";
            String zipPath = req.getServletContext().getRealPath("/upload/zip") + "/";
            //移动文件位置
            File endDirection = new File(zipPath + "temp");
            for (String s : filePathArray) {
                //获得文件路径
                String filePath = s;
                //文件位置
                File startFile = new File(realPath+filePath);
                //如果不存在就创建
                if(!endDirection.exists()) {
                    endDirection.mkdirs();
                }
                FileUtil.copy(startFile, endDirection, false);
            }
            ZipUtil.zip(zipPath+"temp", zipPath+zipName, false);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(zipName, "UTF-8"));
            String zipsPath = req.getServletContext().getRealPath("/upload/zip") + "/";
            File file = new File(zipsPath + zipName);
            ResponseEntity<byte[]> r = new ResponseEntity<>(FileUtil.readBytes(file), httpHeaders, HttpStatus.CREATED);
            //删除文件夹
            if(endDirection.exists()) {
                FileUtil.del(endDirection);
                FileUtil.del(file);
            }else {
                FileUtil.del(file);
            }
            return r;
        } else {
            return null;
        }
    }

}
